import React from 'react';
import {connect} from 'dva';
import PropTypes from 'prop-types';
import reqwest from 'reqwest';
import {Link} from 'dva/router'
import { Button,Row,Col,Icon,Layout,Input,Form,Breadcrumb,Select,Affix,DatePicker ,Checkbox,Modal,message,Cascader,notification} from 'antd';
import style from '../../styles/ResetInput.less';
import inStyle from '../../styles/Info.less';
// import CityPick from '../../components/CityPick.js';
import DateSelect from '../../components/DateSelect.js';
import {numvail,selectvail} from '../../utils/Validator.js'
import {range,disabledDate,disabledDateTime } from '../../utils/Date.js'
import {reqwest_get} from '../../utils/Reqwest.js'
import moment from 'moment';
import options from '../../models/CityData.js';
import {order_list} from '../../utils/ListForm.js'
const FormItem = Form.Item;
const Option =Select.Option;
const AUTH_KEY = {Authorization: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiQ1JNIiwiYXBpX3R5cGUiOiJDUk0iLCJ0b2tlbiI6ImZjZWQ2NjEzZGFmYjQ1NmI4ZDcwMDBlNzI0Yzc2NTU3IiwiZXhwIjoyMTI2MDU5MzEwfQ.NtvCE4BLQ1Ioyum_TIBSg4jyIMk-Y3GumPdlPYg9GuI'}
const phoneReg =/^1[34578]\d{9}$/g;
let _form = [];
class SalerDetails extends React.Component{
	constructor(props){
		super(props)
		this.state={
			result:[],
			channels:window.channels,
			province:null,
			city:null,
			area:null,
			companies:localStorage['companies']===undefined||localStorage['companies']=='undefined'?[]:JSON.parse(localStorage['companies']),
			material:sessionStorage['material']===undefined?[]:JSON.parse(sessionStorage['material']),
			surveyors:[],
			// store_tree:sessionStorage['store_tree']===undefined?[]:JSON.parse(sessionStorage['store_tree']),
			store_tree:[],
			list:null,
			cgj_id:window.localStorage['cgj_id']=='null'||window.localStorage['cgj_id']==null||window.localStorage['cgj_id']==undefined||window.localStorage['cgj_id']=='undefined'?false:true,
			sto_bol:[],
			loading:false,
			ssss:undefined,
			measure_master:undefined
			// street:null,
		}
	}
	openNotification(){
	  const key = `open${Date.now()}`;
	  const btnClick = function () {
	    // to hide notification box
	    window.location.hash='/app/newcha'
	    notification.close(key);
	  };
	  const btn = (
	    <Button type="primary" size="small" onClick={btnClick}>
	      点击跳转
	    </Button>
	  );
	  notification.open({
	    message: '提示',
	    description: '您当前的门店数量为空,请点击按钮进行创建门店',
	    duration:null,
	    btn,
	    key,
	    // onClose: close,
	  });
	};
	handleSearch(e,b){
		console.log(b)
		reqwest_get('/api/orders/fetch_users',{
			access_token:window.localStorage['token'],
			keyword:e
		},(data)=>{
			// console.log(data)
			this.setState({surveyors:data.surveyors});
		})
	}
	getServer(){
		// debugger;
		// this.setState({loading:true});
		let _this = this;
		reqwest({
      url: window.host+'/api/pres',
      method: 'get',
      crossOrigin: true,
	    // headers:AUTH_KEY,
  	  // contentType: 'application/json',
  	  data:{
  	  	access_token:window.localStorage['token']
  	  },
      type: 'json',
    }).then((data) => {
    	// console.log(data);
    	// sessionStorage['companies']=JSON.stringify(data.companies);
    	// sessionStorage['material']=JSON.stringify(data.libs);
    	// if(data.select_companies[0].stores_tree.children.length<1){
    	// 	_this.openNotification()
    	// }
    	// this.setState({store_tree:data.stores_tree,companies:data.companies});
    	this.setState({store_tree:data.stores_tree,companies:data.select_companies});
    	// window.localStorage['companies']=JSON.stringify(data.select_companies);
    }).fail( (err, msg) =>{
       console.log(1)
       // this.setState({loading:true});
    })
	}
	componentWillMount(){
		// console.log(this.props.location.query.wudi);
		this.getServer();
		// if(this.props.location.query.wudi!=undefined){
		// 	this.setState({list:JSON.parse(this.props.location.query.wudi)})
		// }
	}
	componentDidMount(){
		this.setState({cgj_id:!!this.state.cgj_id});
	}
	loadserver (params = {}) {
    // console.log('params:', params);
    this.setState({loading:true});
    let _data=[];
    // return
    let _this = this;
    reqwest({
      url: window.host+'/api/orders',
      method: 'post',
      crossOrigin: true,
      data: {
        access_token:localStorage['token'],
        id:params.id,
        order:{expected_square:params.order.expected_square,booking_date:params.order.booking_date,
        	cgj_company_id:JSON.parse(params.order.cgj_company_id).a,material:params.order.material.a,material_id:params.order.material.b,
        	store_id:params.order.store_id,region_id:params.order.region_id,introducer_name:params.order.introducer_name,introducer_tel:params.order.introducer_tel,total:params.order.total,
        	estimated_total:params.order.estimated_total,cgj_customer_service_id:_this.state.measure_master,measure_master:params.order.cgj_customer_service_id
        },
        customer:{name:params.customer.name,tel:params.customer.tel,province:params.customer.province,city:params.customer.city,area:params.customer.area,street:params.customer.street,},
        remark:params.remark
      },
      type: 'json',
    }).then((data) => {
    		if(data.status=='success'){
	    		message.success('下单成功', 0.5,()=>{
	    			window.location.hash='/app/orders?current='+_this.props.location.query.current;
	   		  })
	   		}else{
	   			this.setState({loading:false});
					message.warning(data.msg,1)
	   		}
    	// console.log(data);
    }).fail( (err, msg) =>{
    		this.setState({loading:false});
        message.error('服务器出错啦', 0.5,()=>{
    			// window.location.hash='/app/orders'
   		  })
    })

  }
  handleCheckChange(e,b){
  	// this.setState({cgj_id:false})
  	let _this = this;
  	// console.log(b)
  	_this.setState({cgj_id:false});
  	if(e.target.checked){
  		Modal.confirm({
  			title:'授权窗管家',
  			content:<p> 授权<a>窗管家</a>访问你的账号</p>,
  			okText:'授权 ',
  			cancelText:'取消',
  			onOk:()=>{
  				reqwest({
  					url:window.host+'/api/auth/cgj',
  					method:'get',
  					data:{access_token:localStorage['token']},
  					type:'json',
  				}).then((data)=>{
  					console.log(data)
  					if(data.status=='success'){
  						window.localStorage['cgj_id']=data.current_user.cgj_user_id;
  						this.setState({cgj_id:true});
  						message.success('授权成功', 0.5,()=>{
			    			// window.location.hash='/app/orders'
			   		  })
  					}else{
  						this.setState({cgj_id:false});
  						message.error('服务器出错啦', 0.5);
  					}
  				}).fail( (err, msg) =>{
  					this.setState({cgj_id:false})
			      // console.log(1)
			    })
  			},
  			onCancel:()=>{
  				// _this.setState({cgj_id:false});
  				_this.state.cgj_id=false;
  				e.target.checked=false;
  				message.error('没有绑定哦', 0.5,()=>{

  				});
  				// console.log(this.state.cgj_id)
  			}
  		})
  	}else{
  		this.setState({cgj_id:false})
  	}
  	// console.log(this.state.cgj_id)
  }
  // handleCityChange(e,obj){
  // 	this.setState({
  // 		province:obj[0]==undefined?undefined:obj[0].label,
  // 		city:obj[1]==undefined?undefined:obj[1].label,
  // 		area:obj[2]==undefined?undefined:obj[2].label,
  // 		// street:obj[3]==undefined?undefined:obj[3].label
  // 	})
  // }
	handleSubmit(e){
    // console.log(e)
    e.preventDefault();
    const {province, city,area,street,list} =this.state;
    let _this =this;
    let _surveyors;
    this.props.form.validateFields((err, values) => {
    	// console.log(values.surveyors.split('~') , '1')
    	// return
      if (!err) {
        // console.log('Received values of form: ', values);

        // console.log(values.caizhi)
        _surveyors = values.surveyors != undefined ? values.surveyors.split('~') : [null]
      	_this.loadserver({
      		id:_this.props.location.query.id,
      		order:{expected_square:values.size,booking_date:_this.state._date,cgj_company_id:values.company,
      			material:JSON.parse(values.caizhi),store_id:values.region,region_id:JSON.parse(values.store).value,
      			introducer_name:values.introducer_name,introducer_tel:values.introducer_tel,total:values.total,
      			estimated_total:values.estimated_total,
      			cgj_customer_service_id:_surveyors[0],measure_master:_surveyors[0]
      		},
      		customer:{name:values.name,tel:values.mobile,province:values.city[0],city:values.city[1],area:values.city[2],street:values.address},
      		remark:values.remark
      	})
      }
    });
	}
	render(){
		// console.log(this.state.cgj_id)
		const {result,channels,companies,material,list,cgj_id,sto_bol} =this.state;
		const formItemLayout = {
      labelCol: { span: 7},
      wrapperCol: { span: 17 },
      // style:{minWidth:200}
    };
    let regionsNode =null;
    let storeNode=null;
    let storeInit=null;
    let aaa=0;
    // _checkbox= !!cgj_id;
    // if(this.state.store_tree.children!=[]){
	   // 	  storeNode = this.state.store_tree.map(function(data){
	   // 			// console.log(data)
	   // 			aaa++;
				// 	return <Option value={'{"id":'+aaa+',"value":'+data.id+',"children":'+JSON.stringify(data.children)+'}'}  key={'b'+data.id} >{data.name}</Option>
				// })
	   //  }
	   console.log(list)
    if(this.state.ssss!=undefined){
    	console.log(companies[this.state.ssss.b])
    	// if(companies[this.state.ssss.b].stores_tree.children!=[]){
	   	  storeNode = companies[this.state.ssss.b].stores_tree.map(function(data){
	   			// console.log(data)
	   			aaa++;
					return <Option value={'{"id":'+aaa+',"value":'+data.id+',"children":'+JSON.stringify(data.children)+'}'}  key={'b'+data.id} >{data.name}</Option>
				})
	    // }

    }
    if(sto_bol.length!=[]&&sto_bol!=undefined){
    	console.log(sto_bol)
    	if(JSON.parse(sto_bol).children.length==0){
    		regionsNode=<Option value="null">当前渠道下无门店</Option>
    		storeInit='当前渠道下无门店'

    		// return
    	}
    	regionsNode=JSON.parse(sto_bol).children.map(function(data){
    		storeInit=data.id;
    		return <Option value={''+data.id}  key={'b'+data.id} >{data.name}</Option>
    	})
    }
    let _this = this;
		const {getFieldDecorator, getFieldsValue,resetFields}=this.props.form;
		let _math = 0;
		const selectNode = companies.map(function(data,index){
			// console.log(data)
			return <Option value={'{"a":'+data.cgj_id+',"b":'+index+'}'} data-index={index}  key={data.id} >{data.name}</Option>
		})
		const materialNode = material.map(function(data){
			return <Option value={'{"a":'+'"'+data.name+'"'+',"b":'+'"'+data.id+'"'+'}'}  key={data.id} >{data.name}</Option>
		})
		// console.log(this.state.surveyors.length)
		// if()
		let _surveyors=this.state.surveyors.length===0?undefined:this.state.surveyors.map((data)=>{
			// console.log(1)
			return <Option value={''+data.name} title={''+data.id} key={''+data.id} >{data.name}</Option>
		})

		const OrderList = order_list.map((data,index)=>{
			return <Row key={index+'a'}>
				{data.map((data1,index1)=>{
					return	<Col key={index1} className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
						<FormItem {...formItemLayout} label={data1.label}>
							{getFieldDecorator(data1.id,{
								initialValue:this.props.location.query[data1.id],
								rules:data1.rule
							})(
								<Input className={`${style.ncc_reset_input_doublie}`} placeholder={data1.label} />
							)}
						</FormItem>
					</Col>

				})}
				</Row>
		})

		return(
			<Layout >
				<Layout.Content className={`${style.berad}`} >
					<Row>
						<Breadcrumb  className={`${style.blue_dia_none}`}>
							<Breadcrumb.Item ><span className={`${style.blue_dia}`}></span></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div} ${style.bread_div_first}`}><Link to={{pathname:'/app/orders',query:{current:this.props.location.query.current}}}>订单</Link></Breadcrumb.Item>
              <Breadcrumb.Item className={`${style.bread_div}`}>新建销售订单</Breadcrumb.Item>
	       		</Breadcrumb>
	       	</Row>
				</Layout.Content>
				<Layout style={{background:'#fff'}}>
				<Form className={`${inStyle.ncc_left_layout}`}  style={{marginTop:26}} onSubmit={this.handleSubmit.bind(this)}>
       		{OrderList}
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem {...formItemLayout} label='地址'>
								{getFieldDecorator('city',{
									// initialValue:'boy'
									rules:[{required:true,message:'请选择地址',validator:(rule,value,callback)=>{
										selectvail(rule,value,callback,'请选择地址')
									}}]
								})(
									<Cascader className={`${style.ncc_reset_input_doublie}`} onChange={this.props.onChange}  style={{border:'none'}} options={options}  showSearch  placeholder='省市区' />
								)}
							</FormItem>
						</Col>
						<Col sm={{span :8,pull:0}} className={`${style.reset_col}`} xs={{span:24,pull:3}}>
							<FormItem {...formItemLayout} label='详细地址'>
								{getFieldDecorator('address',{
									initialValue:list==null?null:list.street,
									rules:[{required:true,message:'请输入具体地址',validator:(rule,value,callback)=>{
										selectvail(rule,value,callback,'请输入具体地址')
									}}]
								})(
									<Input  className={`${style.ncc_reset_input_doublie}`} placeholder='具体地址' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='品牌商'>
								{getFieldDecorator('company',{
									initialValue:list!==null?(list.company_id+''):undefined,
									rules:[{required:true,message:'请选择品牌商',}]
								})(
									<Select  onChange={(e)=>{this.setState({ssss:JSON.parse(e),sto_bol:[]});resetFields(['store':undefined])}} placeholder='品牌商' className={`${style.ncc_reset_border_doublie}`} optionFilterProp='children' showSearch>
										{selectNode}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col sm={{span :8,pull:0}} className={`${style.reset_col}`} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='材质'>
								{getFieldDecorator('caizhi',{
									initialValue:list!==null?('{"a":"'+list.material+'","b":"'+list.material_id+'"}'):undefined,
									rules:[{required:true,message:'请选择材质'}]
								})(
									<Select  placeholder='材质'  default className={`${style.ncc_reset_border_doublie}`} onChange={(e)=>{console.log(e)}} optionFilterProp='children' showSearch>
										{materialNode}
									</Select>
								)}
							</FormItem>
						</Col>
					</Row>
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='渠道'>
								{getFieldDecorator('store',{
									initialValue:list!==null?('{"a":'+'"'+list.company_id+'"'+',"b":'+'"'+list.id+'"'+'}'):undefined,
									rules:[{required:true,message:'请选择渠道',}]
								})(
									<Select  placeholder='请选择渠道' onChange={(e,b)=>{this.setState({sto_bol:e});console.log(b)}} className={`${style.ncc_reset_border_doublie}`} optionFilterProp='children' showSearch>
										{storeNode}
									</Select>
								)}
							</FormItem>
						</Col>
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem help='需先选择渠道在选择门店' {...formItemLayout} label='门店'>
								{getFieldDecorator('region',{
									initialValue:this.state.sto_bol.length==0?undefined:storeInit+'',
									rules:[{message:'请选择门店'}]
								})(
									<Select  disabled={this.state.sto_bol.length==0}  className={`${style.ncc_reset_border_doublie}`} placeholder='请选择门店' onChange={(e)=>{console.log(e)}} optionFilterProp='children' showSearch>
										{regionsNode}
									</Select>
								)}
							</FormItem>
						</Col>
					</Row>
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem className={`${style.date_reset_input}`}{...formItemLayout} label='预约时间' >
								{getFieldDecorator('date',{
									initialValue:list==null?null:moment(list.booking_date, 'YYYY-MM-DD'),
									rules:[{required:true,message:'请选择时间'}]
								})(
									<DatePicker
										placeholder='预约测量时间'
									  onChange={(e,b)=>{this.setState({_date:b})}}
										style={{width:'100%'}}
							      format="YYYY-MM-DD HH:mm:ss"
							      disabledDate={disabledDate}
							      showTime
							    />
								)}
							</FormItem>
						</Col>
						<Col sm={{span :8,pull:0}} className={`${style.reset_col}`} xs={{span:24,pull:3}} >
							<FormItem  {...formItemLayout} label='预估面积'>
								{getFieldDecorator('size',{
									initialValue:list==null?null:list.square,
									rules:[{required:true,message:'请输入面积',pattern:/\d+/,validator:(rule,value,callback)=>{
										if(!value){
											callback('请输入面积')
										}else if(!rule.pattern.test(value)){
											callback('请输入数字')
										}
										callback();
									}}]
								})(
									<Input  min={0} onChange={(e)=>{console.log(e.target.value)}}  className={`${style.ncc_reset_input_doublie}`} placeholder='预估面积(/m²)' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row >

						<Col sm={{span :8,pull:0}} className={`${style.reset_col}`} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='服务费' >
								{getFieldDecorator('total',{
									initialValue:list==null?null:list.square,
									rules:[{required:true,message:'请输入面积',pattern:/\d+/,validator:(rule,value,callback)=>{
										if(!rule.pattern.test(value)){
											callback('请输入数字')
										}else if(!value){
											callback('请输入正确的格式')
										}
										callback();
									}}]
								})(
									<Input min={0} className={`${style.ncc_reset_input_doublie}`} placeholder='服务费(/元)' />
								)}
							</FormItem>
						</Col>
						<Col sm={{span :8,pull:0}} className={`${style.reset_col}`} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='产品价格' >
								{getFieldDecorator('estimated_total',{
									initialValue:list==null?null:list.square,
									rules:[{required:true,message:'请输入预估产品价格',pattern:/\d+/,validator:(rule,value,callback)=>{
										if(!rule.pattern.test(value)){
											callback('请输入数字')
										}else if(!value){
											callback('请输入正确的格式')
										}
										callback();
									}}]
								})(
									<Input min={0} className={`${style.ncc_reset_input_doublie}`} placeholder='预估产品价格(/元)' />
								)}
							</FormItem>
						</Col>
       		</Row>
       		<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}} >
							<FormItem {...formItemLayout} label='选择师傅'>
								{getFieldDecorator('surveyors',{
									// initialValue:this.state.surveyors.length==0?undefined:''+this.state.surveyors[0].id+'~'+this.state.surveyors[0].name,
									rules:[{nessage:'请选择师傅'}]
								})(
								  <Select  placeholder='选择师傅'  onSearch={(e,b)=>{this.handleSearch(e,b)}} onSelect={(e,opt)=>this.setState({measure_master:opt.props.title})} default className={`${style.ncc_reset_border_doublie}`} optionFilterProp='children' showSearch>
										{_surveyors}
									</Select>
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row>
						<Breadcrumb style={{ height:60,lineHeight:'60px',fontSize:14}}>
              <Breadcrumb.Item>介绍人<span style={{fontSize:12}}>(选填项)</span></Breadcrumb.Item>
	       		</Breadcrumb>
       		</Row>
					<Row >
						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem help='' {...formItemLayout} label='介绍人'>
								{getFieldDecorator('introducer_name',{
									// initialValue:'boy'
									rules:[{message:'请选择介绍人'}]
								})(
									<Input className={`${style.ncc_reset_input_doublie}`} placeholder='介绍人' />
								)}
							</FormItem>
						</Col>

						<Col className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem {...formItemLayout} label='电话'>
								{getFieldDecorator('introducer_tel',{
									rules:[{message:'请输入介绍人电话',validator:(rule,value,callback)=>{
										let phoneReg =/^1[34578]\d{9}$/g;
										if(!value){
											callback();
										}else if(!phoneReg.test(value)){
											callback('手机格式不正确');
										}
										console.log(!value)
										callback()
									}}]
								})(
									<Input className={`${style.ncc_reset_input_doublie}`} placeholder='介绍人电话' />
								)}
							</FormItem>
						</Col>
					</Row>
					<Row >
						<Col  className={`${style.reset_col}`} sm={{span :8,pull:0}} xs={{span:24,pull:3}}>
							<FormItem help='默认返利为2%，如果需要变更请联系管理员' {...formItemLayout} label='返利'>
								{getFieldDecorator('fanli',{
									initialValue:'2'
								})(
									<Input className={`${style.ncc_reset_input_doublie}`} addonAfter="%"  placeholder='返利' />
								)}
							</FormItem>
						</Col>
					</Row>
       		<Row >
						<Breadcrumb style={{ height:60,lineHeight:'60px',fontSize:14}}>
              <Breadcrumb.Item>备注<span style={{fontSize:12}}>(选填项)</span></Breadcrumb.Item>
	       		</Breadcrumb>
       		</Row>
       		<Row>
	       		<Col className={`${style.reset_col}`}  span={8}>
								<FormItem {...formItemLayout} label='备注'>
								{getFieldDecorator('remark',{
									initialValue:this.props.location.query.remark,
								})(
									<Input style={{height:'100px'}} type='textarea' className={`${style.ncc_reset_input} `} placeholder='备注:' />
								)}
							</FormItem>
						</Col>
       		</Row>
       		<Row style={{marginBottom:15}}>
       			<Col xl={{offset:3}} lg={{offset:2}} sm={{span :8,pull:0}} xs={{span:17,pull:3}} >

							<Checkbox defaultChecked={cgj_id}  checked={cgj_id}  onChange={this.handleCheckChange.bind(this)}>下单至窗管家</Checkbox>
							<p style={{fontSize:12}}>需授权"窗管家"</p>
						</Col>
					</Row>
					<Row>
	       		<Col xl={{offset:3}} lg={{offset:2}} sm={{span :8,pull:0}} xs={{span:17,pull:3}}  >
		       		<div  style={{float:'left'}} >
		       			<FormItem >
			            <Button loading={this.state.loading} htmlType="submit" size='large' type="primary"  >
			              保存
			            </Button>
		          	</FormItem>
		          </div>
		          <div  style={{float:'left',marginLeft:10}} >
		          	<Button size='large'  >
			              <Link to={{pathname:'/app/orders',query:{current:this.props.location.query.current}}}>取消</Link>
			          </Button>
		          </div>
	          </Col>
          </Row>
				</Form>
			</Layout>
			</Layout>
		)
	}
}


const SalerDetailsForm = Form.create()(SalerDetails);
export default connect()(SalerDetailsForm)
